package com.tianji.login.service.Impl;

import com.alibaba.fastjson.JSON;
import com.tianji.login.dto.AuthParamsDto;
import com.tianji.login.mapper.SysMenuMapper;
import com.tianji.login.pojo.SysMenu;
import com.tianji.login.pojo.XcUserExt;
import com.tianji.login.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

//注释掉DaoAuthenticationProviderCustom，自定义认证逻辑
@Component
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private SysMenuMapper xcMenuMapper;

    /*
     * @Author 陈佳
     * @Description 根据账号查询用户信息,就是生成jwt令牌
     * @Date 15:50 2023/5/31
     * @Param [s:账号]
     * @return org.springframework.security.core.userdetails.UserDetails
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        AuthParamsDto authParamsDto = null;

        try {
            authParamsDto = com.alibaba.fastjson.JSON.parseObject(s,AuthParamsDto.class);
        }catch (Exception ex){
            log.info("认证请求不符合项目要求:{}",s);
            throw new RuntimeException("认证请求数据格式不对");
        }

        //调用方法执行校验用户和密码操作
        String authType = authParamsDto.getAuthType();
        AuthService authService = applicationContext.getBean(authType + "_authservice", AuthService.class);
        XcUserExt execute = authService.execute(authParamsDto);

        //返回的时候加上权限,userDetails
        return getUserPrincipal(execute);
    }



    /**
     * @description 查询用户信息
     * @param user  用户id，主键
     * @return com.xuecheng.ucenter.model.po.XcUser 用户信息
     * @author Mr.M
     * @date 2022/9/29 12:19
     */

    public UserDetails getUserPrincipal(XcUserExt user){
        //取出数据库的存储密码
        String password = user.getPassword();

        //从数据库中查询权限并且放入权限
        List<SysMenu> xcMenus = xcMenuMapper.selectPermissionByUserId(user.getUserId());
        //只需要添加code
        List<String> permissions = new ArrayList<>();
        if(xcMenus.size()<=0){
            //用户权限,如果不加则报Cannot pass a null GrantedAuthority collection
            permissions.add("p1");
        }else{
            xcMenus.forEach(menu -> {
                if (menu.getPermission() != null && !menu.getPermission().isEmpty()) {
                    permissions.add(menu.getPermission());
                }
            });
        }
        //转换成数组
        String[] authorities = permissions.toArray(new String[0]);
        //权限也放入jwt令牌中
        user.setPermissions(permissions);

        //======扩展用户身份信息======
        //为了安全在令牌中不放密码
        user.setPassword(null);
        //将user对象转为json
        String userJson = JSON.toJSONString(user);
        //创建UserDetails对象,权限信息待实现授权功能时再向UserDetail中加入
        UserDetails userDetails = User.withUsername(userJson).password(password).authorities(authorities).build();
        return userDetails;
    }
}
